package com.zatech.cgnci.project.controller;


import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zatech.cgnci.project.base.enums.ResponseCodeEnum;
import com.zatech.cgnci.project.base.enums.StatisticalTypeEnum;
import com.zatech.cgnci.project.base.exception.GlobalException;
import com.zatech.cgnci.project.dto.ReportCreateDTO;
import com.zatech.cgnci.project.dto.StatisticalReportDTO;
import com.zatech.cgnci.project.service.CgnciStatisticalReportService;
import com.zatech.cgnci.project.vo.StatisticalReportVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.OutputStream;
import java.net.URLEncoder;

/**
 * <p>
 * 统计报表 前端控制器
 * </p>
 *
 * @author Generator
 * @since 2025-02-19
 */
@RestController
@RequestMapping("/statistical-report")
@RequiredArgsConstructor
@Api(produces = "application/json", tags = "统计报表api接口文档")
public class CgnciStatisticalReportController {

    @Resource
    private CgnciStatisticalReportService statisticalReportService;

    @PostMapping("/page")
    @ApiOperation(value = "分页列表查询")
    public IPage<StatisticalReportVO> page(@RequestBody StatisticalReportDTO queryDTO) {
        return statisticalReportService.pageData(queryDTO);
    }

    @PostMapping("/verify")
    @ApiOperation(value = "数据校验接口-有数据提交后返回id")
    public StatisticalReportVO verify(@RequestBody @Valid StatisticalReportDTO queryDTO) {
        return statisticalReportService.verify(queryDTO);
    }

    @PostMapping("/createReport")
    @ApiOperation(value = "生成报表")
    public void extract(@RequestBody @Valid ReportCreateDTO extractDTO) {
        statisticalReportService.createReport(extractDTO);
    }

    @GetMapping("/exportAll")
    @ApiOperation(value = "统计报表文件下载")
    public void exportProjectAll(HttpServletResponse response, Long registerId, String businessTypeCode) {
        ExcelWriter writer = null;
        try {
            OutputStream outputStream = response.getOutputStream();
            writer = statisticalReportService.export(registerId, businessTypeCode);
            response.setContentType("application/x-download");
            String fileName = URLEncoder.encode(StatisticalTypeEnum.getEnumByCode(businessTypeCode).getName() + ".xlsx", "UTF-8");
            response.setCharacterEncoding("UTF-8");
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
            writer.getWorkbook().write(outputStream);
            response.getOutputStream().flush();
        } catch (Exception e) {
            throw new GlobalException(ResponseCodeEnum.PARAMS_ILLEGAL, "下载文件失败");
        } finally {
            assert writer != null;
            writer.close();
        }
    }
}

